package com.example.security.handler;

import cn.hutool.json.JSONUtil;
import com.example.model.api.Result;
import com.example.model.api.ResultBuilder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class SecurityAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        Result<String> apiResult = ResultBuilder.<String>aResult().msg("认证失败").build();
        writer.write(JSONUtil.toJsonStr(apiResult));
        writer.flush();
        writer.close();
    }
}
